import {createApp, reactive} from '/static/scripts/petite-vue.es.js';
import axios from '/static/scripts/axios.js';
axios.defaults.timeout = 30000;

const instance = reactive({
    sno: '',
    name: '',
    password: '',
    sendRequest: false,
    success: false,
    signedName: '',
    get canSign() {
        return !this.success && (this.sno.length != 0 && this.name.length != 0 && this.password.length != 0)
    },
    get alreadySign() {
        return localStorage.getItem('user') != null;
    },
    set alreadySign(user) {
        localStorage.setItem('user', btoa(encodeURIComponent(JSON.stringify(user))));
    },
    message: '',
    test() {
        console.log(this.sno, this.password);
        axios.post('/sign', {
            sno: this.sno,
            password: this.password
        }).then(res => res.data)
            .then(json => {
                instance.message = json.message;
                instance.success = json.success;
                if (json.success) {
                    instance.alreadySign = {sno: this.sno, name: this.name};
                    this.signedName  = this.name;
                }
            });
        instance.sendRequest = true;
        this.init();
    },
    init() {
        if (this.alreadySign) {
            let userStr = decodeURIComponent(atob(localStorage.getItem('user')));
            let user = JSON.parse(userStr);
            this.signedName = user.name;
        }
    }
});

createApp(instance).mount();